<?php

class myCultureFilter extends sfFilter
{
  public function execute($filterChain)
  {
    // execute this filter only once
    if ($this->isFirstCall())
    {      
      //set internal character encoding for mb_* functions
      mb_internal_encoding('UTF-8');
      mb_regex_encoding('UTF-8');
      
      $con = Propel::getConnection();
      
      if ($con){
         $con->executeQuery("SET NAMES 'utf8'");
         $con->executeQuery("SET CHARACTER SET utf8");
      } else {
        throw new Exception($e);
      }      
    } 

    if($this->getContext()->getRequest()->getParameter('lang'))
    {
      $language = LanguagePeer::retrieveByLang($this->getContext()->getRequest()->getParameter('lang'));
      $culture = ($language instanceof Language) ? $language->getCulture() : sfConfig::get('sf_i18n_default_culture');
      $this->getContext()->getUser()->setCulture($culture);
      $this->getContext()->getUser()->setDir(($language instanceof Language) ? $language->getDir() : sfConfig::get('sf_i18n_default_direction'));
    }
    elseif ($this->getContext()->getRequest()->getCookie('culture'))
    {
      $language = LanguagePeer::retrieveByCulture($this->getContext()->getRequest()->getCookie('culture'));
      $culture = ($language instanceof Language) ? $language->getCulture() : sfConfig::get('sf_i18n_default_culture'); 
      $this->getContext()->getUser()->setCulture($culture);
      $this->getContext()->getUser()->setDir(($language instanceof Language) ? $language->getDir() : sfConfig::get('sf_i18n_default_direction'));
    }
    else
    {     
      $this->getContext()->getUser()->setCulture(sfConfig::get('sf_i18n_default_culture'));
      $this->getContext()->getUser()->setDir(sfConfig::get('sf_i18n_default_direction'));
    }
    
    // set culture cookie
    if( $this->getContext()->getRequest()->getCookie('culture') != $this->getContext()->getUser()->getCulture())
    {                                          
      $this->getContext()->getResponse()->setCookie('culture', $this->getContext()->getUser()->getCulture(), time()+60*60*24*15, '/');
    }
    
    // set page title
    $this->getContext()->getResponse()->setTitle($this->getContext()->getI18n()->__($this->getContext()->getResponse()->getTitle()));
    
    // set culture direction dependant stylesheet
    $this->getContext()->getResponse()->addStylesheet($this->getContext()->getUser()->getDir());

    // execute next filter
    $filterChain->execute();
  }
}
